package com.binguo.wxapi.controller;


import com.binguo.common.util.JsonUtil;
import com.binguo.model.mapper.LogProductImgFromUserMapper;
import com.binguo.model.mapper.ProductMapper;
import com.binguo.model.model.LogProductImgFromUser;
import com.binguo.model.model.Product;
import com.binguo.service.DeviceMsgService;

import com.binguo.wxapi.form.AddProductForm;
import com.binguo.wxapi.result.Result;
import com.binguo.wxapi.result.ResultGenerator;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import tk.mybatis.mapper.entity.Condition;


import javax.annotation.Resource;
import java.util.List;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;



/**
 * Created by haibang on 18/5/7.
 */
@Api(tags = "小程序: 卡包")
@RestController
@RequestMapping
public class WXDeviceMsgController {

    private static Logger logger = LoggerFactory.getLogger(WXDeviceMsgController.class);


    @Autowired
    DeviceMsgService deviceMsgService;

    @Resource
    ProductMapper productMapper;
    @Resource
    LogProductImgFromUserMapper logProductImgFromUserMapper;


    @GetMapping(value = "/api/jaybb", produces = APPLICATION_JSON_VALUE)
    public String adfasdfadasf() throws Exception{
        Condition productCondition = new Condition(Product.class);
        productCondition.or().andEqualTo("shopid", 135);
        List<Product> productList = productMapper.selectByCondition(productCondition);

        for (Product product : productList) {

            Integer newPId = createProduct(product.getName(), product.getPrice());

            Condition condition = new Condition(LogProductImgFromUser.class);
            condition.or().andEqualTo("productId", product.getId());
            List<LogProductImgFromUser> logProductImgFromUserList = logProductImgFromUserMapper.selectByCondition(condition);
            if (logProductImgFromUserList != null && logProductImgFromUserList.size() > 0) {
                for (LogProductImgFromUser temp : logProductImgFromUserList) {
                    if (temp.getImgCutNetUrl() != null) {
                        addProductImg(temp.getImgCutNetUrl(), 250, newPId);
                    }
                }
            }
        }

        return "ok";
    }

    private Integer createProduct(String name, Long price)throws Exception{
        HttpHeaders DEFAULT_JSON_HEADER_UTF8 = new HttpHeaders();
        DEFAULT_JSON_HEADER_UTF8.setContentType(MediaType.APPLICATION_JSON_UTF8);
        AddProductForm addProductForm = new AddProductForm();
        addProductForm.setProductName(name);
        addProductForm.setProductPrice(price.toString());
        addProductForm.setShopId(250);
        addProductForm.setBranchId(282);
        String param = JsonUtil.toJson(addProductForm);
        HttpEntity entity = new HttpEntity<>(param, DEFAULT_JSON_HEADER_UTF8);


        ResponseEntity<String> responseEntity =
                new RestTemplate().postForEntity("http://192.168.10.190/api/wxapp/product/create", entity, String.class);

        Result result = JsonUtil.parse(responseEntity.getBody(), Result.class);

        return (Integer)result.getData();
    }

    private void addProductImg(String fileurl, Integer shopId, Integer productId)throws Exception{

        RestTemplate restTemplate = new RestTemplate();

        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("multipart/form-data");
        headers.setContentType(type);

        //设置请求体，注意是LinkedMultiValueMap
        UrlResource fileSystemResource = new UrlResource(fileurl);
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        form.add("file", fileSystemResource);
        form.add("shopId",shopId);
        form.add("productId",productId);

        HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);

        String s = restTemplate.postForObject("http://192.168.10.190/api/wxapp/productimg/addImg", files, String.class);
        System.out.println(s);


    }

    @PostMapping(value = "/api/wxapp/addDeviceMsg", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "添加消息", notes = "添加消息")
    public Result personcreate(@RequestParam Integer shopId, @RequestParam String faceUrl ,
                               @RequestParam Integer customerId, @RequestParam String customerName
            , @RequestParam String type, @RequestParam String faceId
                               ) {
        logger.info(shopId + ", " + faceUrl + ", " + customerId + "," + customerName + "," + type);
        if (deviceMsgService.addDeviceMsg(shopId, customerId, customerName, faceUrl, type, faceId)) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult("fail");
        }
    }

    @PostMapping(value = "/api/wxapp/cms/addDeviceMsg", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "管理平台审核用户成功添加消息", notes = "添加消息")
    public Result addDeviceMsg(@RequestParam Integer shopId,
                               @RequestParam Integer customerId
                               ) {
        logger.info("shopId== " + shopId + "customerId=== " + customerId);

        if (deviceMsgService.cmsAddDeviceMsg(shopId, customerId)) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult("fail");
        }
    }



}
